#include "TCPClient.h"
#include <iostream>

using namespace std;

TCPClient::TCPClient() {

    running = false;
    WSAStartup(MAKEWORD(2,0), &WSAData);
    sock = socket(AF_INET, SOCK_STREAM, 0);

    }


bool TCPClient::Connect(const string& ip, int port) {

    sin.sin_addr.s_addr = inet_addr(ip.c_str());
    sin.sin_family = AF_INET;
    sin.sin_port = htons(port);
    int r = connect(sock, (SOCKADDR *)&sin, sizeof(sin));
    //TODO: verifier le resultat
    if (r < 0) {
        cout << "Result: " << r << endl;
        return false;
        }
    return true;
    }


void TCPClient::Run() {

    running = true;
    int r,len;
    char rbuffer[255] = "";
    char buffer[255] = "";
    while(running) {
        len = recv(sock, rbuffer, sizeof(rbuffer), 0);
        if (len>0) {
            rbuffer[len] = '\0';
            //color(6,0);
            printf("Var envoye par le serveur : %s \r\n", rbuffer);
            //color(2,0);
            }
        //scanf("%s", &rbuffer);
        cout << "Votre msg: ";
        cout.flush();
        fgets(buffer, sizeof(buffer), stdin);

        if ((r = send(sock, buffer, sizeof(buffer), 0) == SOCKET_ERROR)) {
            printf("envoi de %s a %s rate\n", buffer, inet_ntoa(sin.sin_addr));
            break;
            }
        else
            printf("envoi de %s a %s OK\n", buffer, inet_ntoa(sin.sin_addr));
        } // while

    closesocket(sock);
    WSACleanup();
    delete [] rbuffer;
    running = false;

    }
